<template>
    <div class="home">
        <el-row>
            <el-col :span="6" :offset="3">
                <div class="login-user">
                    当前登录人
                    用户id：【{{userId}}】 <br>
                    用户名称：【{{username}}】<br>
                    用户手机号：【{{phone}}】<br>
                    <el-button type="text" @click="handleLogout()">退出</el-button>
                </div>
                <el-tabs v-model="activeName">
                    <el-tab-pane label="好友" name="p2p">
                        <div class="first-item-list">
                            <template v-for="(item,index) in friendsList">
                                <div class="first-item"
                                     :class="{'first-item-selected':item.id === currentChatUserId}"
                                     @click="handleItemClick(item,index)">
                                    <span>用户【{{item.id}}】</span>
                                    <span>名称：{{item.username}}</span>
                                    <el-button size="mini" @click.stop="handleBlackClick(item)">设置</el-button>
                                </div>
                            </template>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="群组" name="group">
                        <template v-for="(item,index) in groupList">
                            <div class="first-item" :class="{'first-item-selected':item.id === currentChatGroupId}"
                                 @click="handleGroupItemClick(item,index)">
                                <span>组id【{{item.id}}】</span>
                                <span>组名称：{{item.name}}</span>
                            </div>
                        </template>
                    </el-tab-pane>
                    <el-tab-pane label="黑名单" name="black">
                        <div class="first-item-list">
                            <template v-for="(item,index) in blacksList">
                                <div class="first-item">
                                    <span>用户【{{item.id}}】</span>
                                    <span>名称：{{item.username}}</span>
                                    <el-button size="mini" @click.stop="handleRemoveBlackClick(item)">移除</el-button>
                                </div>
                            </template>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </el-col>
            <el-col :span="12">
                <template v-if="(activeName === 'p2p' || activeName === 'group') && (currentChatGroupId != null || currentChatUserId != null)">
                    <msg-content
                            v-if="msgList.length > 0"
                            ref="msgContent" :msg-list="msgList"></msg-content>
                    <send-msg ref="sendMsg" @handlerResult="handlerResult"></send-msg>
                </template>
            </el-col>
        </el-row>

        <div :visible.sync="userListVisible">
            <user-list v-if="userListVisible" ref="usersList" :users-list="usersList" :group-id="currentChatGroupId"></user-list>
        </div>
        <el-dialog title="资料设置" width="350px" :visible.sync="dataSetVisible" append-to-body >
            <data-set v-if="dataSetVisible" ref="dataSet" :friend-id="friendId" :friends-list="friendsList"
                      :blacks-list="blacksList" :current-item="currentItem"></data-set>
        </el-dialog>
        <div class="personal_information">
            <el-button type="text" @click="dialogVisible = true">个人信息</el-button>
            <el-dialog title="个人信息" :visible.sync="dialogVisible"
                       width="30%"
                       :before-close="handleClose">
                <div class="demo-type">
                    <div>
                        <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
                        <span style="margin-left: 500px">头像</span>
                    </div>
                    <hr>
                </div>
                <el-form :model="formLabelAlign">
                    <el-form-item label="昵称">
                        <el-input v-model="formLabelAlign.nickName"></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-input v-model="formLabelAlign.sex"></el-input>
                    </el-form-item>
                    <!--<el-form-item label="二维码">
                        <el-input v-model="formLabelAlign.quickMark"></el-input>
                    </el-form-item>-->
                    <el-form-item label="地址">
                        <el-input v-model="formLabelAlign.address"></el-input>
                    </el-form-item>
                    <el-form-item label="个性签名">
                        <el-input v-model="formLabelAlign.personalizedSignature"></el-input>
                    </el-form-item>
                    <!--<el-form-item>
                        <el-button type="primary" @click="onSubmit()">确认修改</el-button>
                        <el-button>取消</el-button>
                    </el-form-item>-->
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible  = false">取 消</el-button>
                    <el-button type="primary" @click="onSubmit()">确认修改</el-button>
                </div>
            </el-dialog>
        </div>
    </div>

</template>

<script>
    import {mapGetters} from "vuex";
    import {closeWebSocket, initWebSocket, MSG_EVENT, sendGroupMsg, sendMsg} from "_l/socket";
    import {getFriendsByUserId, getGroupByUserId,updateByIdPersonalInformation,getUser} from "_a/user";
    import {getGroupOffMsg, getP2pOffMsg} from "_a/message";
    import SendMsg from "_c/send-msg";
    import MsgContent from "_c/msg-content";
    import {getBlackListByUserId,deleteBlackList} from "_a/blacklist";
    import DataSet from "_c/data-set"
    import UserList from "_c/user-list"
    import {getUserListByGroupId} from "_a/userlist";

    export default {
        name: 'Home',
        components: {MsgContent, SendMsg, DataSet, UserList},
        data() {
            return {
                dialogVisible: false,
                friendsList: [],
                groupList: [],
                blacksList: [],
                // 当前聊天的人
                currentChatUserId: null,
                currentChatGroupId: null,
                activeName: 'p2p',
                msg: null,
                msgList: [],
                // 新消息体
                msgBody: null,
                dataSetVisible: false,
                friendId: null,
                currentItem: null,
                formLabelAlign: {
                    nickName: null,
                    pic: null,
                    account: null,
                    sex: null,
                    address: null,
                    quickMark: null,
                    personalizedSignature: null,
                    id : null
                },
                userListVisible: false,
                usersList: []
            }
        },
        computed: {
            ...mapGetters(['userId', 'username', 'phone'])
        },
        watch: {
            activeName: function (newVal, oldValue) {
                this.userListVisible = false
                if (newVal === 'p2p') {
                    this.currentChatGroupId = null;
                } else {
                    this.currentChatUserId = null;
                }
            }
        },
        methods: {
            handleItemClick(item, index) {
                this.currentChatUserId = item.id;
                this.msgList = [];
                // 获取离线消息
                getP2pOffMsg(this.userId, this.currentChatUserId).then(res => {
                    for (let i = 0; i < res.data.length; i++) {
                        let message = res.data[i].message;
                        res.data[i].message = JSON.parse(message)
                    }
                    this.msgList = res.data;
                })
                this.$nextTick(function () {
                    this.$refs.sendMsg.resVal()
                })
            },
            onSubmit() {
                this.formLabelAlign.id = this.userId;
                updateByIdPersonalInformation(this.formLabelAlign).then(res => {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.dialogVisible = false
                })
            },
            handleGroupItemClick(item, index) {
                this.currentChatGroupId = item.id;
                this.msgList = [];
                getGroupOffMsg(this.currentChatGroupId).then(res => {
                    for (let i = 0; i < res.data.length; i++) {
                        let message = res.data[i].message;
                        res.data[i].message = JSON.parse(message)
                    }
                    this.msgList = res.data;
                })
                //获取群成员
                getUserListByGroupId(this.currentChatGroupId).then(res => {
                    this.usersList = [];
                    this.userListVisible = true;
                    this.usersList = res.data;
                })
                this.$nextTick(function () {
                    this.$refs.sendMsg.resVal()
                })
            },
            getFriendsList() {
                getFriendsByUserId(this.userId).then(res => {
                    if (res.success) {
                        this.friendsList = res.data;
                    }
                })
            },
            getGroupList() {
                getGroupByUserId(this.userId).then(res => {
                    if (res.success) {
                        this.groupList = res.data;
                    }
                })
            },
            handleLogout() {
                this.$store.dispatch('user/logout',this.userId).then(() => {
                    closeWebSocket()
                    this.$nextTick(function () {
                        this.$router.push('/');
                    })
                })
            },
            handleMsgResult(data) {
                switch (data.event) {
                    case MSG_EVENT.P2P:
                    case MSG_EVENT.GROUP:
                        this.msgList.push(data);
                        break;
                    case MSG_EVENT.SERVER:
                        this.$notify.info({
                            title: '成功',
                            message: data.message
                        });
                        break;
                }
            },
            handlerResult(msgBody) {
                this.msgBody = msgBody;
                if (this.activeName === 'p2p') {
                    sendMsg(this.currentChatUserId, this.msgBody)
                } else {
                    sendGroupMsg(this.currentChatGroupId, this.msgBody)
                }
            },
            handleSendMsg() {
                sendMsg(this.currentChatUserId, this.msgBody)
            },
            handleSendGroupMsg() {
                sendGroupMsg(this.currentChatGroupId, this.msgBody)
            },
            handleBlackClick(item) {
                this.dataSetVisible = true
                this.friendId = item.id
                this.currentItem = item
            },
            getBlacksList() {
                getBlackListByUserId(this.userId).then(res => {
                    if (res.success) {
                        this.blacksList = res.data;
                    }
                })
            },
            handleRemoveBlackClick(item) {
                deleteBlackList(this.userId,item.id).then(res => {
                    if(true == res.data){//黑名单移除元素   好友添加元素
                        this.blacksList.splice(this.blacksList.indexOf(item),1)
                        this.friendsList.push(item)
                    }else{
                        let message = '移除黑名单失败'
                        this.$message({
                            type: 'success',
                            message
                        })
                    }
                })
            },
            handleClose(done) {
                /*this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});*/
                this.dialogVisible  = false
            },
            getPersonalizedSignature(userId){
                getUser(userId).then(data =>{
                    this.formLabelAlign.pic = data.data.pic;
                    this.formLabelAlign.account = data.data.account;
                    this.formLabelAlign.address = data.data.address;
                    this.formLabelAlign.nickName = data.data.nickName;
                    this.formLabelAlign.personalizedSignature = data.data.personalizedSignature;
                    this.formLabelAlign.quickMark = data.data.quickMark;
                    this.formLabelAlign.sex = data.data.sex;
                })
            }
        },
        mounted() {
            this.getFriendsList();
            this.getGroupList();
            this.getBlacksList();
            this.getPersonalizedSignature(this.userId)
            // 初始化webSocket
            initWebSocket(this.handleMsgResult);
        }
    }
</script>

<style scoped>
    .home {
        padding: 30px;
    }

    .login-user {
        height: 100px;
    }

    .first-item {
        display: flex;
        justify-content: space-between;
        border-radius: 2px;
        border: 1px solid #DCDFE6;
        padding: 10px;
        margin: 10px 0 10px 0;
        cursor: pointer;
    }

    .first-item-selected {
        background: #409EFF;
    }
    .personal_information{
        position: absolute;
        right: 50px;
        margin-top: -400px;
    }
</style>
